package com.example.config.securityConfig.authAction;

import com.alibaba.fastjson.JSON;
import com.example.common.utils.ApiResult;
import com.example.dao.TUserMapper;
import com.example.model.entity.TUser;
import com.example.model.query.TUserQuery;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.stream.Collectors;

@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${jwt.token-header-key}")
    private String tokenHeaderKey; //token响应头Key
    @Value("${jwt.token-secret}")
    private String tokenSecret; //token秘钥
    @Value("${jwt.token-expiration}")
    private Long tokenExpiration; //token过期时间

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("utf-8");    //设置 HttpServletResponse使用utf-8编码
        httpServletResponse.setHeader("Content-Type", "text/html;charset=utf-8");  //设置响应头的编码
        ApiResult result = new ApiResult();
        TUserQuery user = (TUserQuery) authentication.getPrincipal();
        // 生成token并设置响应头
        Claims claims = Jwts.claims();
        claims.put("role", authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()));
        claims.put("userInfo",user);
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject("username") //设置用户名
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) //设置token过期时间
                .signWith(SignatureAlgorithm.HS512, tokenSecret).compact(); //设置token签名算法及秘钥
        httpServletResponse.addHeader(tokenHeaderKey,  token); //设置token响应头
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html;charset=UTF-8");
        result.setCode(0);
        result.setMessage(token);
        result.setData(user);
        httpServletResponse.getWriter().write(JSON.toJSON(result).toString());
    }
}

